package com.hethongviet.vending.pages;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.google.android.DemoKit.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.db.BoxSQLite;
import com.hethongviet.vending.helper.db.ProductSQLite;
import com.hethongviet.vending.helper.db.ProductServiceSQLite;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.ProductService;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONSTANTS;
import com.hethongviet.vending.network.Network;

public class DetailBoxActivity extends GeneralActivity
{
	private Button _buttonServiceAddProduct = null;
	private Button _buttonServiceChangeProduct = null;
	private Button _buttonServiceChangeProductPrice = null;
	private Button _buttonServiceIncreaseAmount = null;
	private Button _buttonServiceDescreaseAmount = null;

	private TextView _textProductAmount = null;
	private TextView _textProductCode = null;
	private TextView _textProductName = null;
	private TextView _textProductPrice = null;
	private TextView _textProductDescription = null;

	private TimerOutUtils _timerOutUtils = null;

	private BoxSQLite _boxSqLite = null;
	private ProductSQLite _productSqLite = null;
	private ProductServiceSQLite _productServiceSQLite = null;

	public DetailBoxActivity()
	{
		_boxSqLite = new BoxSQLite(this);
		_productSqLite = new ProductSQLite(this);
		_productServiceSQLite = new ProductServiceSQLite(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_detail_box);

		findViewById(R.id.button_back).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				finish();
			}
		});

		((TextView) findViewById(R.id.text_detail_box_title)).setText(String.format(
				getString(R.string.box_detail_title),
				AppMain.getInstance().getCurrentBoxItemIndex() + 1));

		((TextView) findViewById(R.id.text_detail_box_code)).setText(AppMain.getInstance().getCurrentBox().getId()
				+ "");

		Product currentProduct = AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getProduct();

		_textProductAmount = ((TextView) findViewById(R.id.text_detail_box_product_amount));
		_textProductCode = ((TextView) findViewById(R.id.text_detail_box_product_code));
		_textProductName = ((TextView) findViewById(R.id.text_detail_box_product_name));
		_textProductPrice = ((TextView) findViewById(R.id.text_detail_box_product_price));
		_textProductDescription = ((TextView) findViewById(R.id.text_detail_box_product_description));

		if (currentProduct != null)
		{
			_textProductAmount.setText(""
					+ AppMain.getInstance().getCurrentBox().getProductAmount());
			_textProductCode.setText(currentProduct.getCode());
			_textProductName.setText(currentProduct.getName());
			_textProductPrice.setText("" + currentProduct.getPrice());
			_textProductDescription.setText(currentProduct.getDescription());
		}
		else
		{
			_textProductAmount.setText("---");
			_textProductCode.setText("---");
			_textProductName.setText("---");
			_textProductPrice.setText("---");
			_textProductDescription.setText("---");
		}

		// ((TextView) findViewById(R.id.text_user_name))
		// .setText(AppMain.getInstance()._accountCurrent.getName());

		((TextView) findViewById(R.id.text_user_name)).setVisibility(View.GONE);

		_buttonServiceChangeProduct = (Button) findViewById(R.id.button_service_change_product);
		_buttonServiceAddProduct = (Button) findViewById(R.id.button_service_add_product);
		_buttonServiceChangeProductPrice = (Button) findViewById(R.id.button_service_change_product_price);
		_buttonServiceDescreaseAmount = (Button) findViewById(R.id.button_service_descrease_product);
		_buttonServiceIncreaseAmount = (Button) findViewById(R.id.button_service_increase_product);

		if (!isHasProduct())
		{
			_buttonServiceChangeProductPrice.setVisibility(View.GONE);
			_buttonServiceDescreaseAmount.setVisibility(View.GONE);
			_buttonServiceIncreaseAmount.setVisibility(View.GONE);
			_buttonServiceChangeProduct.setVisibility(View.GONE);
			_buttonServiceAddProduct.setVisibility(View.VISIBLE);
		}
		else
		{
			_buttonServiceChangeProductPrice.setVisibility(View.VISIBLE);
			_buttonServiceDescreaseAmount.setVisibility(View.VISIBLE);
			_buttonServiceIncreaseAmount.setVisibility(View.VISIBLE);
			_buttonServiceChangeProduct.setVisibility(View.VISIBLE);
			_buttonServiceAddProduct.setVisibility(View.GONE);
		}

		_buttonServiceChangeProduct.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(DetailBoxActivity.this,
						ChangeProductActivity.class);
				intent.putExtra(Constant.EXTRA_FINISH, 2);
				startActivityForResult(intent,
						InputTextActivity.INPUT_CHANGE_PRODUCT);
			}
		});

		_buttonServiceAddProduct.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(DetailBoxActivity.this,
						ChangeProductActivity.class);
				intent.putExtra(Constant.EXTRA_FINISH, 2);
				startActivityForResult(intent,
						InputTextActivity.INPUT_ADD_PRODUCT);
			}
		});

		_buttonServiceChangeProductPrice.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(DetailBoxActivity.this,
						InputTextActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt(InputTextActivity.KEY_INPUT_TYPE,
						InputTextActivity.INPUT_PRICE);
				bundle.putInt(Constant.EXTRA_FINISH, 2);
				intent.putExtras(bundle);
				startActivityForResult(intent, InputTextActivity.INPUT_PRICE);
			}
		});

		_buttonServiceDescreaseAmount.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(DetailBoxActivity.this,
						InputTextActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt(InputTextActivity.KEY_INPUT_TYPE,
						InputTextActivity.INPUT_PRODUCT_AMOUNT_DESC);
				bundle.putInt(Constant.EXTRA_FINISH, 2);
				intent.putExtras(bundle);
				startActivityForResult(intent,
						InputTextActivity.INPUT_PRODUCT_AMOUNT_DESC);
			}
		});

		_buttonServiceIncreaseAmount.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(DetailBoxActivity.this,
						InputTextActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt(InputTextActivity.KEY_INPUT_TYPE,
						InputTextActivity.INPUT_PRODUCT_AMOUNT);
				bundle.putInt(Constant.EXTRA_FINISH, 2);
				intent.putExtras(bundle);
				startActivityForResult(intent,
						InputTextActivity.INPUT_PRODUCT_AMOUNT);
			}
		});

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, false);

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:
				try
				{
					AppMain.getInstance().setNumberActivityFinishLogout(1);
					showDialog(R.string.message_time_out_user_not_operating);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			case TIME_OUT_USER:
				try
				{
					AppMain.getInstance().setNumberActivityFinishLogout(1);
					showDialog(R.string.message_time_out_user);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			default:
				break;
		}

		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerNotOperating();

		return super.onTouchEvent(event);
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		if (AppMain.getInstance().getNumberActivityFinishLogout() > 0)
		{
			AppMain.getInstance().setNumberActivityFinishLogout(
					AppMain.getInstance().getNumberActivityFinishLogout() - 1);
			finish();
			return;
		}

		_timerOutUtils.startTimerOutUser();
		_timerOutUtils.startTimerNotOperating();

	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();
		super.onPause();
	}

	private boolean isHasProduct()
	{
		String productCode = AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getBox().getProductCode();
		return productCode != null && !productCode.equals("");
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (requestCode == InputTextActivity.INPUT_CHANGE_PRODUCT
					|| requestCode == InputTextActivity.INPUT_ADD_PRODUCT)
			{
				Box currentBox = AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).getBox();
				/* Insert database */
				_boxSqLite.insert(currentBox);

				/* Update all boxes */
				AppMain.getInstance().updateListBoxItems();

				/* Update view */
				Product currentProduct = AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).getProduct();

				/* Update inventory */
				// BoxInventory boxInventory = new BoxInventory();
				// boxInventory.setIdBox(currentBox.getId());
				// boxInventory.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());
				// boxInventory.setProductAmount(currentBox.getProductAmount());
				// boxInventory.setProductCode(currentBox.getProductCode());
				// boxInventory.setDate(System.currentTimeMillis());
				// boxInventory.setSentServerOk(false);
				// _boxInventorySQLite.insert(boxInventory);

				/* Insert product take out */
				ProductService productService = new ProductService();

				Utils.debug("Add/change product");

				/* Insert product change */
				productService = new ProductService();
				productService.setTransaction(ProductService.TRANSACTION_PRODUCT_CHANGE);
				productService.setAmount(0);
				productService.setIdBox(currentBox.getId());
				productService.setCodeProduct(currentBox.getProductCode());
				productService.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());
				productService.setPrice(currentBox.getProductPrice());
				productService.setSentServerOk(false);
				productService.setStaffChecker(AppMain.getInstance().getCurrentAccount().getId());
				productService.setStaffService(AppMain.getInstance().getCurrentAccount().getId());
				productService.setDate(System.currentTimeMillis());

				_productServiceSQLite.insert(productService);

				if (!AppConfig.USE_SEND_ALL_DATA)
				{
					if (AppConfig.IS_NETWORK_AVAILABLE)
					{
						_productServiceSQLite.updateIdDB(productService);
						Network.sendProductChange(productService);
					}
				}

				if (currentProduct != null)
				{
					_textProductAmount.setText(""
							+ AppMain.getInstance().getCurrentBox().getProductAmount());
					_textProductCode.setText(currentProduct.getCode());
					_textProductName.setText(currentProduct.getName());
					_textProductPrice.setText("" + currentProduct.getPrice());
					_textProductDescription.setText(currentProduct.getDescription());

					_buttonServiceChangeProductPrice.setVisibility(View.VISIBLE);
					_buttonServiceDescreaseAmount.setVisibility(View.VISIBLE);
					_buttonServiceIncreaseAmount.setVisibility(View.VISIBLE);
					_buttonServiceChangeProduct.setVisibility(View.VISIBLE);
					_buttonServiceAddProduct.setVisibility(View.GONE);
				}
				else
				{
					_textProductAmount.setText("---");
					_textProductCode.setText("---");
					_textProductName.setText("---");
					_textProductPrice.setText("---");
					_textProductDescription.setText("---");

					_buttonServiceChangeProductPrice.setVisibility(View.GONE);
					_buttonServiceDescreaseAmount.setVisibility(View.GONE);
					_buttonServiceIncreaseAmount.setVisibility(View.GONE);
					_buttonServiceChangeProduct.setVisibility(View.GONE);
					_buttonServiceAddProduct.setVisibility(View.VISIBLE);
				}
			}

			else if (data != null && data.getExtras() != null)
			{
				String dataInput = data.getStringExtra(InputTextActivity.KEY_INPUT_DATA);

				int numberInput = -1;

				try
				{
					numberInput = Integer.parseInt(dataInput);
				} catch (NumberFormatException e)
				{
					e.printStackTrace();
				}

				if (numberInput == -1)
				{
					Utils.debug(" Can not load data from input");
					return;
				}

				switch (requestCode)
				{
					case InputTextActivity.INPUT_PRICE:
						changePrice(numberInput);
						break;
					case InputTextActivity.INPUT_PRODUCT_AMOUNT:
						changeAmount(numberInput);
						break;
					case InputTextActivity.INPUT_PRODUCT_AMOUNT_DESC:
						changeAmount(-numberInput);
						break;

					default:
						break;
				}

			}
		}
		else
			super.onActivityResult(requestCode, resultCode, data);
	}

	private void changePrice(int newPrice)
	{
		AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getProduct().setPrice(
				newPrice);

		/* Insert database */
		_productSqLite.insert(AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getProduct());

		/* Update all boxes */
		AppMain.getInstance().updateListBoxItems();

		/* Update view */
		_textProductPrice.setText("" + newPrice);
	}

	private void changeAmount(int deltaAmount)
	{
		int oldAmount = AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getBox().getProductAmount();
		int newAmount = oldAmount + deltaAmount;

		if (newAmount < 0)
		{
			showDialog(0);
			return;
		}

		AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getBox().setProductAmount(
				newAmount);

		Box currentBox = AppMain.getInstance().getListBoxItems().get(
				AppMain.getInstance().getCurrentBoxItemIndex()).getBox();

		/* Insert database */
		_boxSqLite.insert(currentBox);

		/* Insert product take out/put in */
		ProductService productService = new ProductService();
		if (deltaAmount > 0)
		{
			productService.setTransaction(ProductService.TRANSACTION_PRODUCT_PUT_IN);
			productService.setAmount(deltaAmount);
		}
		else
		{
			productService.setTransaction(ProductService.TRANSACTION_PRODUCT_TAKE_OUT);
			productService.setAmount(-deltaAmount);
		}

		productService.setIdBox(currentBox.getId());
		productService.setCodeProduct(currentBox.getProductCode());
		productService.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());
		productService.setPrice(currentBox.getProductPrice());
		productService.setSentServerOk(false);
		productService.setStaffChecker(AppMain.getInstance().getCurrentAccount().getId());
		productService.setStaffService(AppMain.getInstance().getCurrentAccount().getId());
		productService.setDate(System.currentTimeMillis());
		_productServiceSQLite.insert(productService);
		if (AppConfig.IS_NETWORK_AVAILABLE)
			if (!AppConfig.USE_SEND_ALL_DATA)
			{
				_productServiceSQLite.updateIdDB(productService);
				if (deltaAmount > 0)
				{
					Network.sendProductPutIn(productService);
				}
				else
				{
					Network.sendProductTakeOut(productService);
				}
			}

		/* Update view */
		_textProductAmount.setText("" + newAmount);
	}

	private int _oldAmount = 0;

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
					AppMain.getInstance().setNumberActivityFinishLogout(0);
				}
			};
			dialogMessageConfirmNotOperating.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else if (id == 0)
		{
			return new DialogMessageBack(
					this,
					true,
					String.format(
							getString(R.string.message_input_product_amount_descrease_error),
							_oldAmount), false);
		}
		else
			return super.onCreateDialog(id);
	}

	@Override
	public void onConnectFail(int typeError)
	{
		Utils.debug("Connect fail!.......................");
		hideProgressDialog();

		showDialogWithStatus(typeError);
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		final String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (message == null || message.equals(""))
		{
			Utils.debug("Null message!!!!!!!!");
			return;
		}

		if (transaction.getModel() == null)
		{
			Utils.debug("Model null------------");
		}

		if (transaction.getMethodSent().equals(
				CONSTANTS.SERVICE.ADD_PRODUCT_CHANGE)
				|| transaction.getMethodSent().equals(
						CONSTANTS.SERVICE.ADD_PRODUCT_PUTIN)
				|| transaction.getMethodSent().equals(
						CONSTANTS.SERVICE.ADD_PRODUCT_TAKEOUT))
		{
			if (transaction.getMessageReceived().toUpperCase().contains("OK"))
			{
				ProductService productService = (ProductService) transaction.getModel();
				productService.setSentServerOk(true);
				_productServiceSQLite.insert(productService);
			}
		}
	}
}
